extends Node2D

# === 可配置参数 ===
@export var color: Color
@export var text_list: Array[String] = ["提示1", "提示2", "提示3"]
@export var duration: float = 3.0
@export var fade_time: float = 0.5
@export var spawn_interval: float = 3.0
@export var begin: bool = true
# === 新增：设置Label总数 ===
@export var label_count: int = 5  # 现在可以方便地改为5，或任何数量

# === 内部变量 ===
# 改为用数组统一管理所有Label和计时器
var labels: Array[Label] = []
var timers: Array[float] = []  # -1.0表示空闲， >=0 表示活跃时间
var spawn_timer: float = 0.0
var min_distance: float = 200.0

func _ready():
	# 根据label_count自动查找和初始化Label节点
	_init_labels()
	# 初始化所有计时器为“空闲”状态
	timers.resize(labels.size())
	for i in range(timers.size()):
		timers[i] = -1.0
	# 重置所有Label到初始状态
	for label in labels:
		_reset_single_label(label)
	
	self.modulate = color
	if begin:
		spawn_timer = spawn_interval * 0.5

# === 新增：初始化Label数组 ===
func _init_labels():
	labels.clear()
	# 假设你的Label节点命名依次为 Label1, Label2...
	for i in range(1, label_count + 1):
		var label_node = get_node_or_null("Label" + str(i))
		if label_node:
			labels.append(label_node)
		else:
			print("警告：未找到节点 Label", i)
	
	# 安全验证：如果未找到任何Label，创建一个默认的
	if labels.size() == 0:
		push_error("未找到任何Label子节点，请检查场景。")
		var default_label = Label.new()
		add_child(default_label)
		labels.append(default_label)

# === 新增：单个Label重置 ===
func _reset_single_label(label: Label):
	label.visible = false
	var current_color = label.modulate
	label.modulate = Color(current_color.r, current_color.g, current_color.b, 0)
	label.text = ""
	label.rotation_degrees = 0
	label.position = Vector2.ZERO

func _process(delta):
	if begin:  # 只有begin为true时，才执行生成逻辑
		spawn_timer -= delta
		if spawn_timer <= 0:
			_try_activate_label()
			spawn_timer = spawn_interval
	
	# 更新所有活跃Label的动画
	for i in range(labels.size()):
		_update_label_animation(i, delta)

func _try_activate_label():
	"""尝试激活一个可用的Label"""
	# 1. 寻找一个空闲的Label
	var available_index = -1
	for i in range(labels.size()):
		if timers[i] < 0:  # 计时器小于0表示空闲
			available_index = i
			break
	
	if available_index == -1:
		return  # 所有Label都在使用中
	
	# 2. 获取其他活跃Label的位置，用于距离检查
	var other_active_positions: Array[Vector2] = []
	for i in range(labels.size()):
		if i != available_index and timers[i] >= 0: # 跳过自己，只取活跃的
			other_active_positions.append(labels[i].position)
	
	# 3. 寻找一个合适的位置
	var position = _find_available_position(other_active_positions)
	if position == null:
		return  # 没有找到合适的位置（虽然概率很低）
	
	# 4. 激活这个Label
	_activate_label(available_index, position)

func _find_available_position(other_positions: Array[Vector2]) -> Vector2:
	"""寻找不靠近其他活跃Label的位置"""
	var screen = get_viewport_rect()
	
	for _attempt in range(30):  # 增加尝试次数
		var candidate = Vector2(
			randf_range(40, 1240),
			randf_range(40, 990)
		)
		
		var too_close = false
		for pos in other_positions:
			if pos.distance_to(candidate) < min_distance:
				too_close = true
				break
		
		if not too_close:
			return candidate
	
	# 找不到绝对合适的位置，返回一个随机位置（允许一定程度重叠）
	return Vector2(
		randf_range(40, 1240),
		randf_range(40, 990)
	)

func _activate_label(label_index: int, position: Vector2):
	"""激活指定索引的Label显示随机文本"""
	var label = labels[label_index]
	
	if text_list.size() > 0:
		label.text = text_list[randi() % text_list.size()]
	
	label.rotation_degrees = randf_range(-15.0, 15.0)
	label.position = position
	
	# 初始设为完全透明，开始淡入
	var current_color = label.modulate
	label.modulate = Color(current_color.r, current_color.g, current_color.b, 0)
	label.visible = true
	
	# 启动该Label的计时器
	timers[label_index] = 0.0

func _update_label_animation(label_index: int, delta: float):
	"""更新单个Label的淡入淡出动画"""
	if timers[label_index] < 0:
		return  # Label处于空闲状态
	
	# 更新时间
	timers[label_index] += delta
	var current_time = timers[label_index]
	var label = labels[label_index]
	
	var alpha: float = 0.0
	
	if current_time < fade_time:
		alpha = current_time / fade_time  # 淡入
	elif current_time < duration - fade_time:
		alpha = 1.0  # 完全显示
	elif current_time < duration:
		alpha = 1.0 - (current_time - (duration - fade_time)) / fade_time  # 淡出
	else:
		# 动画结束，重置Label
		timers[label_index] = -1.0
		_reset_single_label(label)
		return
	
	# 应用计算出的透明度
	var current_color = label.modulate
	label.modulate = Color(current_color.r, current_color.g, current_color.b, alpha)

# === 公共控制方法 (需要相应修改) ===
func start_generating():
	"""开始生成文本"""
	begin = true
	spawn_timer = spawn_interval * 0.5

func stop_generating():
	"""停止生成新文本，但允许现有Label完成动画"""
	begin = false

func clear_all_immediately():
	"""立即清除所有Label"""
	begin = false
	for i in range(labels.size()):
		_reset_single_label(labels[i])
		timers[i] = -1.0

func set_text_list(new_list: Array[String]):
	text_list = new_list if new_list.size() > 0 else ["默认文本"]
